<template>
  <div class="selected-course-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('course.selected') }}</span>
        <el-radio-group v-model="viewMode" size="small" style="float: right;">
          <el-radio-button label="selected">{{ $t('course.selected') }}</el-radio-button>
          <el-radio-button label="available">{{ $t('course.available') }}</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 已选课程 -->
      <div v-if="viewMode === 'selected'" v-loading="loading">
        <div class="course-list">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in selectedCourses" :key="item.id" class="course-item">
              <el-card shadow="hover" class="course-card">
                <div class="course-header">
                  <h3 class="course-name">{{ item.name }}</h3>
                  <el-tag size="small" type="success">已选</el-tag>
                </div>
                
                <div class="course-info">
                  <p><i class="el-icon-user"></i> {{ $t('course.teacher') }}：{{ item.teacherName }}</p>
                  <p><i class="el-icon-date"></i> {{ $t('course.duration') }}：{{ formatDate(item.startDate) }} {{ $t('common.to') }} {{ formatDate(item.endDate) }}</p>
                  <p><i class="el-icon-time"></i> {{ $t('course.schedule') }}：{{ item.startTime }} - {{ item.endTime }}</p>
                  <p><i class="el-icon-location"></i> {{ $t('course.location') }}：{{ item.location }}</p>
                  <p class="course-desc"><i class="el-icon-document"></i> {{ $t('course.description') }}：{{ item.info || $t('course.noDescription') }}</p>
                </div>
                
                <div class="course-actions">
                  <el-button type="danger" size="mini" @click="handleUnselect(item)">
                    <i class="el-icon-close"></i> {{ $t('course.withdraw') }}
                  </el-button>
                  <el-button type="info" size="mini" @click="handleView(item)">
                    <i class="el-icon-view"></i> {{ $t('common.detail') }}
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 空状态 -->
          <el-empty v-if="selectedCourses.length === 0" :description="$t('course.noSelectedCourses')"></el-empty>
        </div>
      </div>
      
      <!-- 可选课程 -->
      <div v-else v-loading="loading">
        <div class="search-container">
          <el-form :inline="true" :model="searchForm" class="search-form" size="small">
            <el-form-item :label="$t('course.name')">
              <el-input v-model="searchForm.name" :placeholder="$t('common.pleaseEnter') + $t('course.name')" clearable></el-input>
            </el-form-item>
            <el-form-item :label="$t('course.teacher')">
              <el-input v-model="searchForm.teacherName" :placeholder="$t('common.pleaseEnter') + $t('course.teacherName')" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchAvailableCourses">{{ $t('common.search') }}</el-button>
              <el-button @click="resetSearch">{{ $t('common.reset') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="course-list">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in availableCourses" :key="item.id" class="course-item">
              <el-card shadow="hover" class="course-card">
                <div class="course-header">
                  <h3 class="course-name">{{ item.name }}</h3>
                  <el-tag size="small" type="primary">{{ item.selectedNum }}/{{ item.maxNum }}人</el-tag>
                </div>
                
                <div class="course-info">
                  <p><i class="el-icon-user"></i> {{ $t('course.teacher') }}：{{ item.teacherName }}</p>
                  <p><i class="el-icon-date"></i> {{ $t('course.duration') }}：{{ formatDate(item.startDate) }} {{ $t('common.to') }} {{ formatDate(item.endDate) }}</p>
                  <p><i class="el-icon-time"></i> {{ $t('course.schedule') }}：{{ item.startTime }} - {{ item.endTime }}</p>
                  <p><i class="el-icon-location"></i> {{ $t('course.location') }}：{{ item.location }}</p>
                  <p class="course-desc"><i class="el-icon-document"></i> {{ $t('course.description') }}：{{ item.info || $t('course.noDescription') }}</p>
                </div>
                
                <div class="course-actions">
                  <el-button 
                    type="success" 
                    size="mini" 
                    @click="handleSelect(item)"
                    :disabled="item.selectedNum >= item.maxNum">
                    <i class="el-icon-plus"></i> {{ $t('course.select') }}
                  </el-button>
                  <el-button type="info" size="mini" @click="handleView(item)">
                    <i class="el-icon-view"></i> {{ $t('common.detail') }}
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 空状态 -->
          <el-empty v-if="availableCourses.length === 0" :description="$t('course.noAvailableCourses')"></el-empty>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="availableCourses.length > 0">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[12, 24, 36, 48]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total">
            </el-pagination>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 选课确认对话框 -->
    <el-dialog :title="$t('course.select')" :visible.sync="selectDialogVisible" width="400px">
      <div>
        <p>{{ $t('common.confirm') }}{{ $t('course.select') }} <strong>{{ selectCourse.name }}</strong> ?</p>
        <p>{{ $t('course.teacher') }}: {{ selectCourse.teacherName }}</p>
        <p>{{ $t('course.duration') }}: {{ formatDate(selectCourse.startDate) }} {{ $t('common.to') }} {{ formatDate(selectCourse.endDate) }}</p>
        <p>{{ $t('course.schedule') }}: {{ selectCourse.startTime }} - {{ selectCourse.endTime }}</p>
        <p>{{ $t('course.location') }}: {{ selectCourse.location }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="confirmSelect" :loading="selectLoading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
    
    <!-- 课程详情对话框 -->
    <el-dialog :title="$t('course.title')" :visible.sync="detailDialogVisible" width="600px">
      <div v-if="currentCourse">
        <el-descriptions :column="1" border>
          <el-descriptions-item :label="$t('course.name')">{{ currentCourse.name }}</el-descriptions-item>
          <el-descriptions-item :label="$t('course.teacher')">{{ currentCourse.teacherName }}</el-descriptions-item>
          <el-descriptions-item :label="$t('course.duration')">{{ formatDate(currentCourse.startDate) }} {{ $t('common.to') }} {{ formatDate(currentCourse.endDate) }}</el-descriptions-item>
          <el-descriptions-item :label="$t('course.schedule')">{{ currentCourse.startTime }} - {{ currentCourse.endTime }}</el-descriptions-item>
          <el-descriptions-item :label="$t('course.location')">{{ currentCourse.location }}</el-descriptions-item>
          <el-descriptions-item :label="$t('course.capacity')">{{ currentCourse.selectedNum }}/{{ currentCourse.maxNum }}</el-descriptions-item>
          <el-descriptions-item :label="$t('course.description')">{{ currentCourse.info }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "SelectedCourse",
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem("userInfo") || "{}"),
      viewMode: 'selected',
      loading: false,
      
      // 已选课程
      selectedCourses: [],
      
      // 可选课程
      availableCourses: [],
      allAvailableCourses: [], // 存储所有可选课程
      
      // 搜索表单
      searchForm: {
        name: '',
        teacherName: '',
        current: 1,
        size: 12
      },
      
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 12,
        total: 0
      },
      
      // 选课对话框
      selectDialogVisible: false,
      selectCourse: {},
      selectLoading: false,
      
      // 详情对话框
      detailDialogVisible: false,
      currentCourse: null
    }
  },
  created() {
    // 确保用户信息已加载
    this.checkUserInfo();
    this.loadData();
  },
  watch: {
    viewMode(newVal) {
      if (newVal === 'selected') {
        this.getSelectedCourses();
      } else {
        this.getAvailableCourses();
      }
    }
  },
  methods: {
    // 检查用户信息是否完整
    checkUserInfo() {
      // 尝试重新获取用户信息
      const userInfoStr = sessionStorage.getItem("userInfo");
      if (userInfoStr) {
        try {
          this.userInfo = JSON.parse(userInfoStr);
          //console.log('用户信息加载成功:', this.userInfo);
        } catch (e) {
          console.error(this.$t('user.loginRequired'), e);
          this.$message.error(this.$t('user.loginRequired'));
        }
      } else {
        console.warn(this.$t('user.loginRequired'));
        this.$message.warning(this.$t('user.loginRequired'));
      }
    },
    loadData() {
      if (!this.userInfo || !this.userInfo.userId) {
        console.warn(this.$t('user.loginRequired'));
        this.$message.warning(this.$t('user.loginRequired'));
        this.loading = false;
        return;
      }
      
      if (this.viewMode === 'selected') {
        this.getSelectedCourses();
      } else {
        this.getAvailableCourses();
      }
    },
    getSelectedCourses() {
      if (!this.userInfo || !this.userInfo.userId) {
        console.warn(this.$t('user.loginRequired'));
        this.$message.warning(this.$t('user.loginRequired'));
        this.loading = false;
        return;
      }
      
      this.loading = true;
      this.$axios.get(`/course/student/${this.userInfo.userId}`).then(res => {
        if (res.code === 200) {
          this.selectedCourses = res.data || [];
          // 获取教师信息
          this.getTeacherInfo();
        } else {
          this.$message.error(res.data.msg || this.$t('course.getCoursesError'));
        }
      }).catch(err => {
        console.error(this.$t('course.getCoursesError'), err);
        this.$message.error(this.$t('course.getCoursesError'));
      }).finally(() => {
        this.loading = false;
      });
    },
    getAvailableCourses() {
      if (!this.userInfo || !this.userInfo.userId) {
        console.warn(this.$t('user.loginRequired'));
        this.$message.warning(this.$t('user.loginRequired'));
        this.loading = false;
        return;
      }
      
      this.loading = true;
      
      // 使用正确的API路径
      this.$axios.get(`/course/available/${this.userInfo.userId}`).then(res => {
        if (res.code === 200) {
          // 保存所有课程数据
          this.allAvailableCourses = res.data || [];
          
          // 执行过滤和分页
          this.filterAndPaginateAvailableCourses();
          
          // 获取教师信息
          this.getTeacherInfo();
        } else {
          this.$message.error(res.data.msg || this.$t('course.getCoursesError'));
        }
      }).catch(err => {
        console.error(this.$t('course.getCoursesError'), err);
        this.$message.error(this.$t('course.getCoursesError'));
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 前端过滤和分页
    filterAndPaginateAvailableCourses() {
      // 过滤课程
      let filteredCourses = this.allAvailableCourses;
      
      // 按课程名称过滤
      if (this.searchForm.name) {
        const searchName = this.searchForm.name.toLowerCase();
        filteredCourses = filteredCourses.filter(course => 
          course.name && course.name.toLowerCase().includes(searchName)
        );
      }
      
      // 按教师名称过滤
      if (this.searchForm.teacherName) {
        const searchTeacherName = this.searchForm.teacherName.toLowerCase();
        filteredCourses = filteredCourses.filter(course => 
          course.teacherName && course.teacherName.toLowerCase().includes(searchTeacherName)
        );
      }
      
      // 更新总数
      this.pagination.total = filteredCourses.length;
      
      // 分页
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      this.availableCourses = filteredCourses.slice(start, end);
    },
    
    searchAvailableCourses() {
      this.pagination.currentPage = 1;
      this.filterAndPaginateAvailableCourses();
    },
    
    resetSearch() {
      this.searchForm = {
        name: '',
        teacherName: '',
        current: 1,
        size: 12
      };
      this.pagination.currentPage = 1;
      this.filterAndPaginateAvailableCourses();
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.filterAndPaginateAvailableCourses();
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.filterAndPaginateAvailableCourses();
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleDateString();
    },
    handleSelect(row) {
      this.selectCourse = row;
      this.selectDialogVisible = true;
    },
    confirmSelect() {
      if (!this.userInfo || !this.userInfo.userId) {
        console.warn(this.$t('user.loginRequired'));
        this.$message.warning(this.$t('user.loginRequired'));
        this.selectDialogVisible = false;
        return;
      }
      
      this.selectLoading = true;
      const selectedCourseDTO = {
        courseId: this.selectCourse.id,
        userId: this.userInfo.userId
      };
      
      //console.log('选课请求参数:', selectedCourseDTO);
      this.$axios.post('/selectedCourse/select', selectedCourseDTO).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('common.operationSuccess'));
          this.selectDialogVisible = false;
          
          // 刷新数据
          this.loadData();
        } else {
          this.$message.error(res.data.msg || this.$t('common.operationFailed'));
        }
      }).catch(err => {
        console.error(this.$t('common.operationFailed'), err);
        this.$message.error(this.$t('common.operationFailedRetry'));
      }).finally(() => {
        this.selectLoading = false;
      });
    },
    handleUnselect(row) {
      this.$confirm(`${this.$t('common.deleteConfirm')} ${row.name}？`, this.$t('common.tip'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.confirmUnselect(row);
      }).catch(() => {});
    },
    confirmUnselect(course) {
      if (!this.userInfo || !this.userInfo.userId) {
        console.warn(this.$t('user.loginRequired'));
        this.$message.warning(this.$t('user.loginRequired'));
        return;
      }
      
      this.loading = true;
      const selectedCourseDTO = {
        courseId: course.id,
        userId: this.userInfo.userId
      };
      
      //console.log('退课请求参数:', selectedCourseDTO);
      this.$axios.post('/selectedCourse/unselect', selectedCourseDTO).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('common.operationSuccess'));
          
          // 刷新数据
          this.loadData();
        } else {
          this.$message.error(res.data.msg || this.$t('common.operationFailed'));
        }
      }).catch(err => {
        console.error(this.$t('common.operationFailed'), err);
        this.$message.error(this.$t('common.operationFailedRetry'));
      }).finally(() => {
        this.loading = false;
      });
    },
    handleView(row) {
      this.currentCourse = row;
      this.detailDialogVisible = true;
    },
    getTeacherInfo() {
      // 获取所有课程的教师ID
      const teacherIds = new Set();
      if (this.viewMode === 'selected') {
        this.selectedCourses.forEach(course => {
          if (course.userId) teacherIds.add(course.userId);
        });
      } else {
        this.availableCourses.forEach(course => {
          if (course.userId) teacherIds.add(course.userId);
        });
      }
      
      if (teacherIds.size === 0) return;
      
      // 获取教师信息
      this.$axios.get('/user/list', {
        params: {
          current: 1,
          size: 100,
          roleType: 'teacher'
        }
      }).then(res => {
        if (res.code === 200) {
          const teachers = res.data.records || [];
          
          // 更新课程的教师名称
          if (this.viewMode === 'selected') {
            this.selectedCourses = this.selectedCourses.map(course => {
              const teacher = teachers.find(t => t.id === course.userId);
              return {
                ...course,
                teacherName: teacher ? teacher.name : this.$t('course.unknownTeacher')
              };
            });
          } else {
            this.availableCourses = this.availableCourses.map(course => {
              const teacher = teachers.find(t => t.id === course.userId);
              return {
                ...course,
                teacherName: teacher ? teacher.name : this.$t('course.unknownTeacher')
              };
            });
          }
        } else {
          console.warn('获取教师信息失败:', res.data.msg);
        }
      }).catch(err => {
        console.error('获取教师信息失败', err);
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.selected-course-container {
  padding: 10px;
}

@media screen and (min-width: 768px) {
  .selected-course-container {
    padding: 20px;
  }
}

.search-container {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.course-list {
  margin-top: 20px;
}

.course-item {
  margin-bottom: 20px;
}

.course-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.course-name {
  margin: 0;
  font-size: 16px;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-info {
  flex: 1;
}

.course-info p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.course-info i {
  margin-right: 5px;
  width: 16px;
  color: #909399;
}

.course-desc {
  margin-top: 10px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-actions {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}

@media screen and (min-width: 768px) {
  .pagination-container {
    text-align: right;
  }
}
</style> 